package cn.tnar.parkservice.service.impl;

import cn.tnar.parkservice.mapper.TSysRoleMapper;
import cn.tnar.parkservice.model.entity.TSysRole;
import cn.tnar.parkservice.model.response.SysRoleResponse;
import cn.tnar.parkservice.model.response.SysRoleResponseDto;
import cn.tnar.parkservice.service.SysRoleService;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xinZhang
 * @Date: 2019/9/29
 * @Description:
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<TSysRoleMapper, TSysRole> implements SysRoleService {

    @Autowired
    private TSysRoleMapper tSysRoleMapper;


    @Override
    public ResultJson querySysRoles(Map<String, Object> param) {
        Integer pageNo = (Integer) param.get("pageNo");
        Integer pageSize = (Integer) param.get("pageSize");
        Page<SysRoleResponse> page = new Page<>(pageNo, pageSize);
        List<SysRoleResponse> list = tSysRoleMapper.querySysRoles(page, param);
        page.setRecords(list);
        return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
    }

    @Override
    public ResultJson querySysRolesTree(Map<String, Object> param) {
        //获取根节点
        SysRoleResponseDto root = tSysRoleMapper.queryRootSysRoles(param);
        if (root != null) {
            SysRoleResponseDto roleTree = getRoleTree(root);
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(roleTree);
        }
        return null;
    }


    private SysRoleResponseDto getRoleTree(SysRoleResponseDto sysRoleResponseDto) {
        Long id = sysRoleResponseDto.getId();
        List<SysRoleResponseDto> list = tSysRoleMapper.querySubListByParentId(id);
        sysRoleResponseDto.getChilds().addAll(list.parallelStream().collect(Collectors.toList()));
        for (SysRoleResponseDto dto : list) {
            getRoleTree(dto);
        }
        return sysRoleResponseDto;
    }
}
